﻿namespace DailyPoetryH.Library.Pages;

using Microsoft.JSInterop;

public partial class Photo {
    private bool _isPhotoAvailable = false;

    private bool _isLoading = true;

    private string _poetry = string.Empty;

    private async Task CaptureAsync() {
        var bytes = await _photoService.CaptureAsync();
        if (bytes is null) {
            return;
        }

        await PoetrilizeAsync(bytes);
    }

    private async Task PickAsync() {
        var bytes = await _photoService.PickAsync();
        if (bytes is null) {
            return;
        }

        await PoetrilizeAsync(bytes);
    }

    private async Task PoetrilizeAsync(byte[] bytes) {
        _isPhotoAvailable = true;
        _isLoading = true;
        StateHasChanged();

        await _jsRuntime.InvokeVoidAsync("setImage",
            new DotNetStreamReference(new MemoryStream(bytes)), "image");

        var poetry = await _poetrilizationService.PoetrilizeAsync(bytes);
        _isLoading = false;
        StateHasChanged();

        if (poetry is null) {
            return;
        }

        _poetry = poetry;
        StateHasChanged();
    }
}